from django.shortcuts import render
from .models import *
from django.http import HttpRequest,HttpResponse,JsonResponse,HttpResponseRedirect
from django.views.decorators.http import require_http_methods
from django.views.decorators.csrf import csrf_exempt
from django.core import serializers
from django.db import connection
from lxml import etree
from fdcl.settings import BASE_DIR,WEIXIN_MP
from django.contrib.auth.decorators import login_required

import json,subprocess,datetime,time,os,requests,hashlib,re,math,ssl,random,csv

import fdcl.settings
from django.contrib.auth import authenticate, login
from django.core import serializers

# forms.py
from django import forms

from django.db.models import Q,Count
from qcloudsms_py import SmsSingleSender
from qcloudsms_py.httpclient import HTTPError
from .views import *
from welink.views import writelog
from welink.models import *


# Create your views here.

#我的档案
#@login_required
@csrf_exempt
def route(request,methodstr = None):
    assert isinstance(request,HttpRequest)
    error_code,return_object = 90000,''
    try:
        #防止注入
        if not re.match(r'^([a-z0-9A-Z]_?)+$',methodstr):
            return JsonResponse({'code':4400,'result':'有注入风险!'})
        
        #无需登录的API
        nologin = ['send_code','get_jsapi_ticket']

        #如果是本地调试
        if not methodstr in nologin and not request.user.is_authenticated and not request.META['HTTP_HOST']=='127.0.0.1:8000':
            return JsonResponse({'code':4000,'result':'没有权限！'})
        
        if request.META['HTTP_HOST']=='127.0.0.1:8000' and not request.user.is_authenticated:
            login(request,User.objects.get(username = 'admin'))

        
        #登录用户
        user = '匿名'
        if request.user.is_authenticated:
            user = request.user.username

        if request.user.is_authenticated and request.user.userprofile:
            user += ' ' + request.user.userprofile.fullname

        body = '%s %s'%(request.method,request.get_full_path())

        if request.method == "POST":
            body  +=  '\n' + str(request.body)



        error_code,return_object = eval(methodstr + "(request)")

        body += '\n' + json.dumps({'code':error_code,'result':return_object})

        writelog('route','mangehe.views_api.%s'% methodstr,body,error_code,user)
    
    except Exception as ex:

        writelog('route','mangehe.views_api.%s'% methodstr,str(ex),50000)
        raise ex

    return JsonResponse({'code':error_code,'result':return_object,'message':return_object['message'] if 'message' in return_object else ''})


def party_next(request):
    assert isinstance(request,HttpRequest)
    if Party.objects.filter(open_time__gt = datetime.datetime.now()).exists():
        u = UserProfile.objects.get(user = request.user)
        o =  Party.objects.filter(open_time__gt = datetime.datetime.now()).order_by('open_time').first()
        jp = JoinParty.objects.get(userprofile = u,party_id = o.id) if JoinParty.objects.filter(userprofile = u,party_id = o.id).exists() else None
        return 20000,{'id':o.id,'name':o.name,'open_time':o.open_time.strftime('%Y/%m/%d %H:%M:%S'),'join_time':jp.join_time.strftime('%Y/%m/%d %H:%M:%S') if jp else ''}
    else:
        return 200,{'message':'找不到下次活动时间!'}


def party_in(request):
    assert isinstance(request,HttpRequest)
    u = UserProfile.objects.get(user = request.user)
    jp,c = JoinParty.objects.get_or_create(userprofile = u,party_id = request.GET.get('id',0))
    return 20000,{'join_time':jp.join_time.strftime('%Y/%m/%d %H:%M:%S')}
    
